package ch.rouge66.energymonitor;
import java.sql.Timestamp;

import ch.rouge66.energymonitor.dao.EnergyLogEntryDao;
import ch.rouge66.energymonitor.dao.EntityManager;

import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

/**
 * @author Marcel Roth
 * @version V1.0, 23.08.2014
 *
 */
public class EnergyMonitorStateChangeEventListener implements GpioPinListenerDigital {

	private static final int TIME_DIFF_THRESHOLD = 1000;
	private long lastTimestamp = 0;
	private long currentTimestamp = 0;
	private EntityManager entityMgr;
	private EnergyLogEntryDao energyLogEntryDao;

	public EnergyMonitorStateChangeEventListener(EntityManager entityMgr, EnergyLogEntryDao energyLogEntryDao) {
		super();
		this.entityMgr = entityMgr;
		this.energyLogEntryDao = energyLogEntryDao;
	}

	public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
		// get current timestamp
		currentTimestamp = System.currentTimeMillis();
		// check for time difference threshold
		if (currentTimestamp - lastTimestamp > TIME_DIFF_THRESHOLD && PinState.HIGH.equals(event.getState())) {
			//
			Timestamp timestamp = new Timestamp(currentTimestamp);
			EnergyLogEntry energyLogEntry = new EnergyLogEntry(null, timestamp, event.getPin().getName(), PinState.HIGH.toString());
			//
			entityMgr.beginTransaction();
			energyLogEntryDao.create(energyLogEntry);
			entityMgr.commitTransaction();
		}
		setLastTimestamp(currentTimestamp);
	}

	long getCurrentTime() {
		return currentTimestamp;
	}

	long getLastTimestamp() {
		return lastTimestamp;
	}

	void setLastTimestamp(long lastTimestamp) {
		this.lastTimestamp = lastTimestamp;
	}

	EntityManager getEntityMgr() {
		return entityMgr;
	}

	void setEntityMgr(EntityManager entityMgr) {
		this.entityMgr = entityMgr;
	}

	EnergyLogEntryDao getEnergyLogEntryDao() {
		return energyLogEntryDao;
	}

	void setEnergyLogEntryDao(EnergyLogEntryDao energyLogEntryDao) {
		this.energyLogEntryDao = energyLogEntryDao;
	}
}
